package it.low.game.client.gui;

import it.low.game.client.util.ClientLogManager;

import java.awt.DisplayMode;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.image.BufferStrategy;

import javax.swing.JFrame;

public class ScreenManager {

	GraphicsDevice graphicsDevice;
	
	public ScreenManager(){
		GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
		graphicsDevice = graphicsEnvironment.getDefaultScreenDevice();
	}
		
	public void setFullScreen(DisplayMode displayMode, JFrame jFrame){
		jFrame.setUndecorated(true);
		jFrame.setResizable(false);
		
		graphicsDevice.setFullScreenWindow(jFrame);
				
		try{
			graphicsDevice.setDisplayMode(displayMode);
		}catch (IllegalArgumentException iae) {
			if(displayMode!=null){
				ClientLogManager.logErr("display width = "+displayMode.getWidth(),null);
				ClientLogManager.logErr("display height = "+displayMode.getHeight(),null);
				ClientLogManager.logErr("display bitRate = "+displayMode.getBitDepth(),null);
			}else{
				ClientLogManager.logErr("displayMode is null",null);
			}
			ClientLogManager.logErr(iae.getMessage(),iae);		
		}catch (UnsupportedOperationException uoe) {
			ClientLogManager.logErr(uoe.getMessage(),uoe);	
		}
	}
		
	public JFrame getFullScreenWindow(){
		return (JFrame)graphicsDevice.getFullScreenWindow();
	}
	
	public void restoreScreen(){
		Window window = this.getFullScreenWindow();
		if(window!=null){
			window.dispose();
		}
		graphicsDevice.setFullScreenWindow(null);
	}
	
	public Graphics2D getGraphics() {
		Window window = graphicsDevice.getFullScreenWindow();
		if (window != null) {
			BufferStrategy strategy = window.getBufferStrategy();
			return (Graphics2D)strategy.getDrawGraphics();
		}else {
			return null;
		}
	}
	
	public void update() {
		Window window = graphicsDevice.getFullScreenWindow();
		if (window != null) {
			BufferStrategy strategy = window.getBufferStrategy();
			if (!strategy.contentsLost()) {
				strategy.show();
			}
		}
		Toolkit.getDefaultToolkit().sync();
	}
	
}
